<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\model\MeituanLogic;

/**
 * 美团授权管理
 *
 * @icon fa fa-circle-o
 */
class MeituanAuth extends Backend
{


    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    /**
     * MeituanAuth模型对象
     * @var \app\admin\model\MeituanAuth
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\MeituanAuth;
        $this->view->assign("sessionStatusList", $this->model->getSessionStatusList());
    }


    //https://wqbanchangdikaifa.kaifa.yimaoqi.cn/addons/ymq_changdi/public/backend.php/meituan_auth/callback?id=3&auth_code=2620f4f6133226d54852d1aa0dd8e3177f90ad8f&state=3
    //https://wqbanchangdikaifa.kaifa.yimaoqi.cn/addons/ymq_changdi/public/backend.php/meituan_auth/callback?id=2&auth_code=88b25aebbae2317b462505ffdc3cf12674f3cecc&state=2
    public function callback()
    {

        $id=$this->request->get('id');
        $auth_code=$this->request->get('auth_code');
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if (empty($auth_code)) {
            $this->error(__('授权码数据为空!'));
        }
        $state=$this->request->get('state');

        $redirect_uri= "https://".$_SERVER['HTTP_HOST']."/addons/ymq_changdi/public/backend.php/meituan_auth/callback?id=".$id;

        $auth_token_res=MeituanLogic::GetAuthToken(
            $row['app_key'],
            $row['app_secret'],
            $auth_code,
            $state,
            $redirect_uri
        );
        $auth_token_json=json_decode($auth_token_res, true);
        //string(139) "{"code":641,"msg":"授权码内容不匹配-redirect_url","access_token":null,"expires_in":0,"remain_refresh_count":0,"tokenType":"bearer"}"
        if ($auth_token_json['code']!==200){
            $this->error($auth_token_json['msg'],url("admin/meituan_auth/index"));
        }
        //https://wqbanchangdikaifa.kaifa.yimaoqi.cn/addons/ymq_changdi/public/backend.php/meituan_auth/callback?id=3&auth_code=ed16b1c4c9bf337f448a4b2286a3ecba9d394424&state=3
        //更新授权码
        $this->model->where('id',$id)->update([
            "session"=>$auth_token_json['access_token'],
            "refresh_session"=>$auth_token_json['refresh_token'],
            "update_time"=>date("Y-m-d H:i:s"),
            'session_status'       => 1,
            'last_refresh_time'    => date('Y-m-d H:i:s'),
        ]);

        $this->success(__('授权成功!'),url("admin/meituan_auth/index"));
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function start_auth($id)
    {
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        //https://wqbanchangdikaifa.kaifa.yimaoqi.cn/addons/ymq_changdi/public/backend.php/meituan_auth?ref=addtabs

        //https://wqbanchangdikaifa.kaifa.yimaoqi.cn/addons/ymq_changdi/public/backend.php/meituan_auth/callback?ref=addtabs

        // $redirect_uri= "http://".$_SERVER['HTTP_HOST']."/api/meituan_auth/callback";

        // $redirect_uri= "http://".$_SERVER['HTTP_HOST']."/addons/ymq_changdi/public/index.php/api/meituan_auth/callback";
        $redirect_uri= "https://".$_SERVER['HTTP_HOST']."/addons/ymq_changdi/public/backend.php/meituan_auth/callback?id=".$id;
        $auth_url=MeituanLogic::GetAuthUrl(
            $row['app_key'],
            $redirect_uri,
            $row['id']
        );
        $this->view->assign("row", $row);
        $this->view->assign("auth_url", $auth_url);
        return $this->view->fetch();
    }


    //更新门店
    public function get_shop_list($id)
    {
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $data=MeituanLogic::getShopList(
            $row['app_key'],
            $row['app_secret'],
            $row['session'],
            $row['bid']
        );
        if ($data['code']!==200){
            $this->error($data['msg']);
        }
        //删除此授权记录下的门店表中的数据
        $shop_model=new \app\admin\model\MeituanShop();
        $shop_model->where('meituan_auth_id',$id)->delete();

        // var_dump($data['data']);exit();
        //遍历门店数据,将门店数据插入到门店表中
        foreach ($data['data'] as $shop){
            $shop_model->insert([
                "meituan_auth_id"=>$id,
                "shop_name"=>$shop['shopname'],
                "city_name"=>$shop['cityname'],
                "shop_address"=>$shop['shopaddress'],
                "open_shop_uuid"=>$shop['open_shop_uuid'],
                "create_time"=>date("Y-m-d H:i:s"),
                "update_time"=>date("Y-m-d H:i:s"),
            ]);
        }
        $this->success('已更新门店', null, $data);
    }


    public function refresh_session($id)
    {
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $result=MeituanLogic::RefreshSession(
            $row['app_key'],
            $row['app_secret'],
            $row['refresh_session']
        );
        if ($result['code']!==200){
            $this->error($result['msg']);
        }
        $this->success('刷新完成', null, $result);
    }

    public function query_product($id)
    {
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $data=MeituanLogic::QueryProduct(
            $row['app_key'],
            $row['app_secret'],
            $row['session'],
            "65284a19e73f5962888613daf8a73a89"
            // "65284a19e73f5962888613daf8a73a89"
        );
        if ($data['code']!==200){
            $this->error($data['msg']);
        }
        $this->success('', null, $data);
    }


    /**
     * 返回 花市系统内 支付方式，和支付账号的json关系数据
     * url http://cfmt.test/mHUYGfQdkE.php/meituanAuth/get_all_meituan_shop_json
     */
    public function get_all_meituan_shop_json()
    {
        $data_list=\app\admin\model\MeituanAuth::with('meituan_shop')->select();
        // 因为前端可能不兼容json的数据命名空间，所以，不用上面的进行返回了。
        header('Content-Type:application/json; charset=utf-8');
        echo json_encode($data_list , JSON_UNESCAPED_UNICODE);
    }

}
